class Solution {
public:
    string decodeString(string s) {
        vector<int> v;
        stack<string> st;
        st.push("");
        int n=s.size();
        for(int i=0;i<s.size();)
        {
            if(s[i]>='0'&&s[i]<='9')
            {
                int tmp=0;
                while(i<n&&s[i]>='0'&&s[i]<='9')
                {
                    tmp=tmp*10+(s[i]-'0');
                    i++;
                }   
                v.push_back(tmp);
            }
            else if(s[i]=='[')
            {
                i++;
                string str;
                while(i<n&&s[i]>='a'&&s[i]<='z')
                {
                    str+=s[i++];
                }
                st.push(str);
            }
            else if(s[i]==']')
            {
                string a=st.top();
                st.pop();
                int b=v.back();
                v.pop_back();
                while(b--)
                {
                    st.top()+=a; 
                }
                i++;
            }
            else
            {
                string c;
                while(i<n&&s[i]>='a'&&s[i]<='z')
                {
                    c+=s[i];
                    i++;
                }
                st.top()+=c;
            }
        }
        return st.top();
    }
};
